import { Button, Col, Form, Input, Modal, Row, Select, Space, Table, message } from 'antd';
import type { TablePaginationConfig, TableProps } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.module.css'
import dayjs from 'dayjs';
import { Image } from 'antd';
import { BookQueryList } from '@/type';
import { bookDelete, getBookList } from '@/api/book';
import Content from '@/components/Content';
import { useRouter } from 'next/router';
import { getCategoryList } from '@/api/category';

interface DataType {
    _id: string;
    name: string;
    age: number;
    address: string
}

export default function Home() {
    const [form] = Form.useForm();
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
            render: (text) => <a>{text}</a>,
        },
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            render: (text) => {
                return <Image width={50} height={50} src={text} alt='' />
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'author',
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            render: (text: { name: string }) => {
                return text?.name
            }
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            width: 200,
            ellipsis: true
        },
        {
            title: '库存',
            dataIndex: 'stock',
            key: 'stock',
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (text: string) => dayjs(text).format('YYYY-MM-DD')
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    {/* <Button type="link">查看</Button> */}
                    <Button type="link" onClick={() => handleEdit(record._id)}>编辑</Button>
                    <Button type="link" danger onClick={() => handleDelete(record._id)}>删除</Button>
                </Space>)
        }
    ];
    const [data, setData] = useState([])
    const Router = useRouter()
    const [pagination, setPagination] = useState<TablePaginationConfig>({
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true
    })
    const [bookOptions, setBookOptions] = useState([]);

    async function fetchData(value?: any) {
        const list = await getBookList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            ...value
        })
        const { data } = list
        setData(data)
        setPagination({
            current: pagination.current, pageSize: pagination.pageSize, total: list.total
        })
        const res = await getCategoryList();
        const categoryList = res.data?.map((item: any) => {
            return {
                label: item.name,
                value: item._id
            }
        })
        setBookOptions(categoryList)
    }

    useEffect(() => {
        fetchData();
    }, [])

    const handleEdit = (id: string) => {
        Router.push('/book/edit/' + id)
    }
    const handleDelete = (id: string) => {
        Modal.confirm({
            title: '确认删除？',
            okText: '确定',
            cancelText: '取消',
            async onOk() {
                await bookDelete(id);
                message.success('删除成功！')
                handleReset()
                fetchData()
            }
        })
    }
    const handleTableChange = async (pagination: TablePaginationConfig) => {
        setPagination(pagination);
        const query = form.getFieldsValue();
        const res = await getBookList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            ...query
        })
        setData(res.data)
    }
    const handleSearch = async (value: BookQueryList) => {
        const res = await getBookList({ ...value, current: 1, pageSize: pagination.pageSize });
        setData(res.data);
        setPagination({ ...pagination, current: 1, total: res.total });

    }
    const handleReset = () => {
        form.resetFields();
    }
    return <Content title="图书列表" operation={<Button type='primary' onClick={() => Router.push('/book/add')}>添加</Button>}>
        <Form
            name="customized_form_controls"
            form={form}
            onFinish={handleSearch}
            initialValues={{
                name: '',
                author: '',
                category: ''
            }}
        >
            <Row gutter={24}>
                <Col span={5}>
                    <Form.Item name="name" label="名称">
                        <Input placeholder='请输入' allowClear />
                    </Form.Item>
                </Col>
                <Col span={5}>
                    <Form.Item name="author" label="作者">
                        <Input placeholder='请输入' allowClear />
                    </Form.Item>
                </Col>
                <Col span={5}>
                    <Form.Item name="category" label="分类">
                        <Select placeholder='请输入' allowClear options={bookOptions} />
                    </Form.Item>
                </Col>
                <Col span={9}>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={handleReset}>重置</Button>
                        </Space>
                    </Form.Item>
                </Col>
            </Row>
        </Form>
        <div className={styles.tableWrap}>
            <Table
                columns={columns}
                dataSource={data}
                rowKey={columns => columns._id}
                onChange={handleTableChange}
                pagination={{ ...pagination, showTotal: () => `共${pagination.total}条` }}
                scroll={{ x: 1000 }} />
        </div>
    </Content>
}
